package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    UserFeign userFeign;
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        // 校验参数
        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }
        if (dto.getSize() == null) {
            dto.setSize(10);
        }
        // 查询评论回复
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime")
                .lt(dto.getMinDate())).limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        // 判断是否登录 如果没有登录的话 就不用返回是否点赞了
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        // 如果登录了 就要返回对每一个评论回复是否点赞的判断
        // 先获得每一个评论的ID
        List<String> repayIds = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        // 根据id获得点赞集合
        List<ApCommentRepayLike> repayLikeList = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId())
                .and("commentRepayId").in(repayIds)), ApCommentRepayLike.class);
        List<String> LikeIds = repayLikeList.stream().map(ApCommentRepayLike::getId).collect(Collectors.toList());
        if (repayLikeList == null||repayLikeList.size()==0) {
            return ResponseResult.okResult(apCommentRepays);
        }
        // 遍历回复集合  封装Vo对象
        List<ApCommentRepayVo> apCommentRepayVoList = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);
            // 判断是否点过赞 点过则operation=0
            if (LikeIds.contains(apCommentRepay.getId())) {
                apCommentRepayVo.setOperation((short) 0);
            }
            apCommentRepayVoList.add(apCommentRepayVo);
        }
        return ResponseResult.okResult(apCommentRepayVoList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        // 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<ApUser> userResponseResult = this.userFeign.findUserById(user.getId());
        if (userResponseResult.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        user = userResponseResult.getData();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "登录信息有误");
        }
        //  保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);

        // 增加评论数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);


        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        // 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 获取点赞行为
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"获取评论实体失败");
        }

        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (commentRepayLike != null && dto.getOperation() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
        }
        if (dto.getOperation() == 0) {
            // 点赞加
            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);
        } else {
            commentRepay.setLikes(commentRepay.getLikes() == 0 ? 0 : commentRepay.getLikes() - 1);
            mongoTemplate.remove(query,ApCommentRepayLike.class);
            mongoTemplate.save(commentRepay);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
